extends "res://BaseEnemy.gd"

# 精英沙漠蠕虫特有属性
@export var burrow_cooldown = 5.0  # 钻地冷却时间
@export var burrow_duration = 1.5  # 钻地持续时间
@export var emerge_damage = 20  # 钻出地面时的伤害
@export var emerge_radius = 50.0  # 钻出地面时的伤害范围

var burrow_timer = 0.0
var is_burrowed = false
var burrow_target_position = Vector2.ZERO
var can_burrow = true

func _ready():
	# 调用父类的_ready方法
	super._ready()
	
	# 设置精英沙漠蠕虫特有属性
	max_health = 120
	current_health = max_health
	movement_speed = 60.0
	damage = 15
	experience_value = 25
	is_elite = true
	
	# 更新生命值条
	if health_bar:
		health_bar.max_value = max_health
		health_bar.value = current_health
	
	# 设置外观
	if sprite:
		sprite.modulate = Color(1.2, 0.8, 0.5)  # 精英沙漠蠕虫颜色

func _physics_process(delta):
	if is_burrowed:
		# 钻地状态下不执行普通的物理处理
		burrow_timer += delta
		if burrow_timer >= burrow_duration:
			emerge()
	else:
		# 非钻地状态下执行普通的物理处理
		super._physics_process(delta)
		
		# 处理钻地冷却
		if not can_burrow:
			burrow_timer += delta
			if burrow_timer >= burrow_cooldown:
				can_burrow = true
				burrow_timer = 0.0
		
		# 如果可以钻地且玩家存在，尝试钻地攻击
		if can_burrow and target_player and is_instance_valid(target_player):
			var distance = global_position.distance_to(target_player.global_position)
			if distance > 100 and distance < 300:  # 在适当距离时使用钻地攻击
				burrow()

func burrow():
	if animation_player and animation_player.has_animation("burrow"):
		animation_player.play("burrow")
		
		# 设置钻地状态
		is_burrowed = true
		burrow_timer = 0.0
		can_burrow = false
		
		# 计算目标位置（玩家位置）
		if target_player and is_instance_valid(target_player):
			burrow_target_position = target_player.global_position
		
		# 视觉效果
		if sprite:
			var tween = create_tween()
			tween.tween_property(sprite, "modulate:a", 0.0, 0.5)  # 淡出
		
		# 禁用碰撞
		$CollisionShape2D.disabled = true
		
		print("精英沙漠蠕虫钻入地下!")

func emerge():
	# 移动到目标位置
	global_position = burrow_target_position
	
	if animation_player and animation_player.has_animation("emerge"):
		animation_player.play("emerge")
	
	# 恢复正常状态
	is_burrowed = false
	burrow_timer = 0.0
	
	# 视觉效果
	if sprite:
		var tween = create_tween()
		tween.tween_property(sprite, "modulate:a", 1.0, 0.3)  # 淡入
	
	# 启用碰撞
	$CollisionShape2D.disabled = false
	
	# 对范围内的玩家造成伤害
	if target_player and is_instance_valid(target_player):
		var distance = global_position.distance_to(target_player.global_position)
		if distance <= emerge_radius:
			target_player.take_damage(emerge_damage)
			
			# 击退效果
			var knockback_direction = (target_player.global_position - global_position).normalized()
			if target_player.has_method("apply_knockback"):
				target_player.apply_knockback(knockback_direction * 200)
	
	print("精英沙漠蠕虫破土而出!")

# 重写受伤方法，钻地状态下不受伤
func take_damage(amount):
	if not is_burrowed:
		super.take_damage(amount)
